import { createSelector, createSlice } from "@reduxjs/toolkit";
import uuid from "uuid-v4";

const incomesSlice = createSlice({
  name: "incomes",
  initialState: {
    list: [],
  },
  reducers: {
    addIncome: (state, action) => {
      state.list.push({
        id: uuid(),
        description: action.payload.description,
        amount: action.payload.amount,
      });
    },
    removeIncome: (state, action) => {
      const index = state.list.findIndex(
        (income) => income.id === action.payload.id
      );
      state.list.splice(index, 1);
    },
  },
});

export const getTotalIncome = createSelector(
  totalIncomeSelector,
  calculateTotalIncome
);

function totalIncomeSelector(state) {
  return state.incomes.list;
}

function calculateTotalIncome(incomesList) {
  // console.log("calculateTotalIncome", incomesList);
  return incomesList.reduce((total, income) => {
    // console.log("income", income);
    return total + income.amount;
  }, 0);
}

export const { addIncome, removeIncome } = incomesSlice.actions;
export const value = incomesSlice;

export default incomesSlice.reducer;
